<template>
  <div class="comment-section">
    <!-- 评论统计 -->
    <div class="comment-header">
      <h3 class="comment-title">
        评论 <span class="comment-count">({{ totalComments }})</span>
      </h3>
      <div class="comment-sort">
        <el-radio-group v-model="sortType" size="small">
          <el-radio-button label="latest">最新</el-radio-button>
          <el-radio-button label="hot">最热</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input-wrapper">
      <el-avatar :size="40" :src="currentUser?.avatar" />
      <div class="input-area">
        <el-input
          v-model="commentContent"
          type="textarea"
          :rows="2"
          :maxlength="1000"
          show-word-limit
          :placeholder="replyTo ? `回复 @${replyTo.name}：` : '写下你的评论...'"
          @focus="handleInputFocus"
        />
        <div class="input-actions">
          <div class="action-left">
            <el-button type="text" @click="handleEmoji">
              <el-icon><Emoji /></el-icon>
              表情
            </el-button>
            <el-button type="text" @click="handleImage">
              <el-icon><Picture /></el-icon>
              图片
            </el-button>
          </div>
          <div class="action-right">
            <el-button v-if="replyTo" text @click="cancelReply">
              取消回复
            </el-button>
            <el-button
              type="primary"
              :disabled="!commentContent.trim()"
              @click="submitComment"
            >
              发布
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="comments.length" class="comment-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <!-- 主评论 -->
        <div class="comment-main">
          <el-avatar
            :size="40"
            :src="comment.author.avatar"
            class="cursor-pointer"
            @click="$router.push(`/user/profile/${comment.author.id}`)"
          />
          <div class="comment-content">
            <div class="comment-info">
              <span
                class="author-name cursor-pointer"
                @click="$router.push(`/user/profile/${comment.author.id}`)"
              >
                {{ comment.author.name }}
              </span>
              <span v-if="comment.author.badge" class="author-badge">
                {{ comment.author.badge }}
              </span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-images" v-if="comment.images?.length">
              <el-image
                v-for="(image, index) in comment.images"
                :key="index"
                :src="image"
                :preview-src-list="comment.images"
                class="comment-image"
              />
            </div>
            <div class="comment-actions">
              <span class="comment-time">{{
                formatTime(comment.createdAt)
              }}</span>
              <div class="action-buttons">
                <el-button
                  :type="props.buttonStyle === 'arco' ? '' : 'text'"
                  :class="[
                    { 'is-liked': comment.isLiked },
                    props.buttonStyle === 'arco' ? 'arco-btn' : ''
                  ]"
                  @click="handleLike(comment)"
                >
                  <el-icon><ThumbsUp /></el-icon>
                  {{ comment.likes || "点赞" }}
                </el-button>
                <el-button 
                  :type="props.buttonStyle === 'arco' ? '' : 'text'"
                  :class="props.buttonStyle === 'arco' ? 'arco-btn' : ''"
                  @click="handleReply(comment)"
                >
                  <el-icon><ChatDotRound /></el-icon>
                  回复
                </el-button>
                <el-dropdown
                  trigger="click"
                  @command="(cmd) => handleAction(cmd, comment)"
                >
                  <el-button 
                    :type="props.buttonStyle === 'arco' ? '' : 'text'"
                    :class="props.buttonStyle === 'arco' ? 'arco-btn' : ''"
                  >
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-if="isCommentAuthor(comment)"
                        command="edit"
                      >
                        编辑
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="isCommentAuthor(comment)"
                        command="delete"
                      >
                        删除
                      </el-dropdown-item>
                      <el-dropdown-item v-else command="report">
                        举报
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>

        <!-- 回复列表 -->
        <div v-if="comment.replies?.length" class="reply-list">
          <div
            v-for="reply in comment.replies"
            :key="reply.id"
            class="reply-item"
          >
            <el-avatar :size="32" :src="reply.author.avatar" />
            <div class="reply-content">
              <div class="reply-info">
                <span class="author-name">{{ reply.author.name }}</span>
                <span v-if="reply.author.badge" class="author-badge">
                  {{ reply.author.badge }}
                </span>
              </div>
              <div class="reply-text">
                <template v-if="reply.replyTo">
                  回复 <span class="reply-to">@{{ reply.replyTo.name }}</span
                  >：
                </template>
                {{ reply.content }}
              </div>
              <div class="reply-actions">
                <span class="reply-time">{{
                  formatTime(reply.createdAt)
                }}</span>
                <div class="action-buttons">
                  <el-button
                    :type="props.buttonStyle === 'arco' ? '' : 'text'"
                    :class="[
                      { 'is-liked': reply.isLiked },
                      props.buttonStyle === 'arco' ? 'arco-btn' : ''
                    ]"
                    @click="handleLike(reply)"
                  >
                    <el-icon><ThumbsUp /></el-icon>
                    {{ reply.likes || "点赞" }}
                  </el-button>
                  <el-button 
                    :type="props.buttonStyle === 'arco' ? '' : 'text'"
                    :class="props.buttonStyle === 'arco' ? 'arco-btn' : ''"
                    @click="handleReply(comment, reply)"
                  >
                    回复
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 查看更多回复 -->
        <div
          v-if="comment.replyCount > comment.replies?.length"
          class="view-more-replies"
          @click="loadMoreReplies(comment)"
        >
          查看更多回复 ({{ comment.replyCount - comment.replies.length }})
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!loading" class="comment-empty">
      <el-empty description="暂无评论" />
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button type="text" :loading="loading" @click="loadMore">
        {{ loading ? "加载中..." : "加载更多" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import {
  Emoji,
  Picture,
  ThumbsUp,
  ChatDotRound,
  More,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
  comments: {
    type: Array,
    default: () => [],
  },
  currentUser: {
    type: Object,
    default: null,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  hasMore: {
    type: Boolean,
    default: false,
  },
  totalComments: {
    type: Number,
    default: 0,
  },
  buttonStyle: {
    type: String,
    default: 'element', // 'element' 或 'arco'
  },
  showFavorite: {
    type: Boolean,
    default: true,
  }
});

const emit = defineEmits([
  "submit",
  "like",
  "reply",
  "edit",
  "delete",
  "report",
  "load-more",
  "load-replies",
]);

// 评论内容
const commentContent = ref("");
const sortType = ref("latest");
const replyTo = ref(null);

// 判断是否为评论作者
const isCommentAuthor = (comment) => {
  return comment.author.id === props.currentUser?.id;
};

// 格式化时间
const formatTime = (time) => {
  // TODO: 根据需求实现时间格式化
  return new Date(time).toLocaleString();
};

// 处理输入框聚焦
const handleInputFocus = () => {
  if (!props.currentUser) {
    ElMessage.warning("请先登录后再评论");
    return false;
  }
  return true;
};

// 处理表情选择
const handleEmoji = () => {
  // TODO: 实现表情选择功能
};

// 处理图片上传
const handleImage = () => {
  // TODO: 实现图片上传功能
};

// 提交评论
const submitComment = () => {
  if (!commentContent.value.trim()) return;

  emit("submit", {
    content: commentContent.value,
    replyTo: replyTo.value,
  });

  commentContent.value = "";
  replyTo.value = null;
};

// 处理回复
const handleReply = (comment, reply = null) => {
  if (!handleInputFocus()) return;

  replyTo.value = reply || comment.author;
  // 滚动到输入框
  document.querySelector(".comment-input-wrapper")?.scrollIntoView({
    behavior: "smooth",
  });
};

// 取消回复
const cancelReply = () => {
  replyTo.value = null;
};

// 处理点赞
const handleLike = (comment) => {
  if (!props.currentUser) {
    ElMessage.warning("请先登录后再点赞");
    return;
  }
  emit("like", comment);
};

// 处理更多操作
const handleAction = async (command, comment) => {
  switch (command) {
    case "edit":
      emit("edit", comment);
      break;
    case "delete":
      try {
        await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        emit("delete", comment);
      } catch {
        // 用户取消删除
      }
      break;
    case "report":
      emit("report", comment);
      break;
  }
};

// 加载更多评论
const loadMore = () => {
  emit("load-more");
};

// 加载更多回复
const loadMoreReplies = (comment) => {
  emit("load-replies", comment);
};
</script>

<style lang="scss" scoped>
.comment-section {
  @apply bg-white rounded-lg;

  .comment-header {
    @apply flex items-center justify-between p-4 border-b border-gray-100;

    .comment-title {
      @apply text-lg font-medium text-gray-900;

      .comment-count {
        @apply text-gray-500 font-normal;
      }
    }
  }

  .comment-input-wrapper {
    @apply flex p-4 border-b border-gray-100;

    .input-area {
      @apply flex-1 ml-3;

      .input-actions {
        @apply flex items-center justify-between mt-2;

        .action-left {
          @apply flex items-center space-x-2;
        }

        .action-right {
          @apply flex items-center space-x-2;
        }
      }
    }
  }

  .comment-list {
    .comment-item {
      @apply border-b border-gray-100 last:border-none;

      .comment-main {
        @apply flex p-4;

        .comment-content {
          @apply flex-1 ml-3;

          .comment-info {
            @apply flex items-center mb-1;

            .author-name {
              @apply font-medium text-gray-900;
            }

            .author-badge {
              @apply ml-2 px-2 py-0.5 text-xs bg-primary-50 text-primary-600 rounded;
            }
          }

          .comment-text {
            @apply text-gray-700 leading-relaxed;
          }

          .comment-images {
            @apply flex flex-wrap gap-2 mt-2;

            .comment-image {
              @apply w-20 h-20 rounded-lg overflow-hidden;
            }
          }

          .comment-actions {
            @apply flex items-center justify-between mt-2;

            .comment-time {
              @apply text-sm text-gray-500;
            }

            .action-buttons {
              @apply flex items-center space-x-2;

              .el-button {
                @apply text-sm;

                &.is-liked {
                  @apply text-primary-600;
                }
                
                &.arco-btn {
                  @apply flex items-center px-3 py-1 rounded-md text-gray-600 bg-gray-100 hover:bg-gray-200 hover:text-primary-600 transition-colors;
                  
                  &.is-liked {
                    @apply text-primary-600 bg-primary-50;
                  }
                  
                  .el-icon {
                    @apply mr-1;
                  }
                }
              }
            }
          }
        }
      }

      .reply-list {
        @apply pl-14 pr-4 pb-4;

        .reply-item {
          @apply flex mt-4;

          .reply-content {
            @apply flex-1 ml-2;

            .reply-info {
              @apply flex items-center mb-1;

              .author-name {
                @apply font-medium text-gray-900;
              }

              .author-badge {
                @apply ml-2 px-2 py-0.5 text-xs bg-primary-50 text-primary-600 rounded;
              }
            }

            .reply-text {
              @apply text-gray-700 text-sm;

              .reply-to {
                @apply text-primary-600;
              }
            }

            .reply-actions {
              @apply flex items-center justify-between mt-1;

              .reply-time {
                @apply text-xs text-gray-500;
              }

              .action-buttons {
                @apply flex items-center space-x-2;

                .el-button {
                  @apply text-sm;

                  &.is-liked {
                    @apply text-primary-600;
                  }
                  
                  &.arco-btn {
                    @apply flex items-center px-3 py-1 rounded-md text-gray-600 bg-gray-100 hover:bg-gray-200 hover:text-primary-600 transition-colors;
                    
                    &.is-liked {
                      @apply text-primary-600 bg-primary-50;
                    }
                    
                    .el-icon {
                      @apply mr-1;
                    }
                  }
                }
              }
            }
          }
        }
      }

      .view-more-replies {
        @apply pl-14 pr-4 pb-4 text-sm text-primary-600 cursor-pointer;
      }
    }
  }

  .comment-empty {
    @apply p-8;
  }

  .load-more {
    @apply flex justify-center p-4;
  }
}
</style>
